package com.uyayo.oms.blog.controller;

import com.uyayo.blog.bo.BlogBO;
import com.uyayo.blog.entity.Blog;
import com.uyayo.blog.model.BlogCondition;
import com.uyayo.blog.model.BlogExCondition;
import com.uyayo.blog.service.BlogService;
import com.uyayo.framework.message.enums.ResultMsgEnum;
import com.uyayo.framework.pagehelper.Pageable;
import com.uyayo.framework.pagehelper.SortOrder;
import com.uyayo.framework.pagehelper.pojo.PageOrderCondition;
import com.uyayo.oms.blog.vo.BlogVO;
import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.pojo.PageResult;
import com.uyayo.system.authority.entity.SysUser;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.ucenter.entity.Member;
import com.uyayo.ucenter.service.MemberService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * BlogController
 * @author 乐乐科技.胡逢君
 * @date 2016-4-23下午4:03:35
 * @version 1.0
 */
@Controller("omsBlogController")
@RequestMapping("/oms/blog/content")
public class BlogController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final ParamBiz paramBiz;

	private final BlogService blogService;

	private  final MessageSource messageSource;

	private final DozerBeanMapper dozerBeanMapper;

	private final MemberService memberService;
	@Autowired
	public BlogController(BlogService blogService, ParamBiz paramBiz, MessageSource messageSource, DozerBeanMapper dozerBeanMapper, MemberService memberService) {
		this.blogService = blogService;
		this.paramBiz = paramBiz;
		this.messageSource = messageSource;
		this.dozerBeanMapper = dozerBeanMapper;
		this.memberService = memberService;
	}

	/**
	 * 页面跳转
	 */
	@RequestMapping(value={"index","/","home"},method=RequestMethod.GET)
	@RequiresPermissions("oms:blog:content:index")
	public ModelAndView index(ModelAndView modelAndView) throws Exception {
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"blog/content/index");
		return modelAndView;
	}

	/**
	 * 获得模型列表
	 */
	@ResponseBody
	@RequestMapping("list")
	@RequiresPermissions("oms:blog:content:search")
	@MethodName(value="博客管理->博客内容管理->查询列表",type=2)
	public List<Blog> list(BlogCondition blogCondition) {
		return blogService.selectBlog(blogCondition);
	}

	@ResponseBody
	@RequestMapping(value="search",method=RequestMethod.GET)
	@MethodName(value="博客管理->博客内容管理->搜索",type=2)
	@RequiresPermissions("oms:blog:content:search")
	public PageResult<Blog> selectBlog(@RequestParam(value = "offset",required = false, defaultValue = "1") Integer start, //第几页
										  @RequestParam(value = "limit", required = false, defaultValue = "10") Integer pageSize,
											 String sort, String order, HttpServletRequest request,BlogCondition blogCondition) throws Exception {
		PageBean<Blog> pageBean= new PageBean<>();
		try {
			Pageable<BlogCondition> pageable  = new Pageable<>();
			pageable.setCurrentPage((start / pageSize) + 1);
			pageable.setPageSize(pageSize);
			List<SortOrder> sortOrders = new ArrayList<>();
			sortOrders.add(new SortOrder(sort,order));
			pageable.setSortOrders(sortOrders);
			String username = blogCondition.getUsername();
			if(!StringUtils.isEmpty(username)){
				Member member = memberService.getMemberByUsername(username);
				if(member==null){
					String message = messageSource.getMessage(ResultMsgEnum.USER_NOT_EXIST.getKey(),new Object[]{}, request.getLocale());
					logger.warn(message);
					PageResult<Blog> pageResult = new PageResult<>();
					pageResult.setRows(pageBean.getList());
					pageResult.setTotal(pageBean.getTotalCount());
					return pageResult;
				}
				blogCondition.setMemberId(member.getId());
			}
			pageable.setCondition(blogCondition);
			pageBean = blogService.selectBlogByPaging(pageable);
		} catch (Exception e) {
			e.printStackTrace();
		}
		PageResult<Blog> pageResult = new PageResult<>();
		pageResult.setRows(pageBean.getList());
		pageResult.setTotal(pageBean.getTotalCount());
		return pageResult;
	}


	@ResponseBody
	@RequestMapping(value="query",method=RequestMethod.GET)
	@MethodName(value="博客管理->博客内容管理->搜索",type=2)
	@RequiresPermissions("oms:blog:content:search")
	public PageResult<BlogBO> selectblogByPaging(@RequestParam(value = "offset",required = false, defaultValue = "0") Integer start, //第几页
									   @RequestParam(value = "limit", required = false, defaultValue = "10") Integer pageSize,
									   String sort, String order, HttpServletRequest request,BlogExCondition blogExCondition) throws Exception {
		PageBean<BlogBO> pageBean= new PageBean<>();
		try {
			String username = blogExCondition.getUsername();
			if(!StringUtils.isEmpty(username)){
				Member member = memberService.getMemberByUsername(username);
				if(member==null){
					String message = messageSource.getMessage(ResultMsgEnum.USER_NOT_EXIST.getKey(),new Object[]{}, request.getLocale());
					logger.warn(message);
					PageResult<BlogBO> pageResult = new PageResult<>();
					pageResult.setRows(pageBean.getList());
					pageResult.setTotal(pageBean.getTotalCount());
					return pageResult;
				}
				blogExCondition.setMemberId(member.getId());
			}

			PageOrderCondition pageOrderCondition = new PageOrderCondition();
			pageOrderCondition.setLimit(pageSize);
			pageOrderCondition.setOffset(start);
			pageOrderCondition.setSort(sort);
			pageOrderCondition.setOrder(order);
			pageBean = blogService.selectBlogByPaging(pageOrderCondition,blogExCondition);
		} catch (Exception e) {
			e.printStackTrace();
		}
		PageResult<BlogBO> pageResult = new PageResult<>();
		pageResult.setRows(pageBean.getList());
		pageResult.setTotal(pageBean.getTotalCount());
		return pageResult;
	}

	/**
	 * 进入新增表单
	 */
	@RequiresPermissions("oms:blog:content:create")
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add() {
		return paramBiz.getManagerTemplatesPrefix()+"blog/content/add";
	}

	/**
	 * 新建
	 */
	@ResponseBody
	@RequiresPermissions("oms:blog:content:create")
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@MethodName(value="博客管理->博客内容管理->新增",type=2)
	synchronized public Result add(HttpServletRequest request, BlogVO blogVO, Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			Blog blog = dozerBeanMapper.map(blogVO,Blog.class);
			blog.setChannelId(1L);
			blog.setCreateTime(new Date());
			blog.setCreateBy(sysUser.getLoginname());
			int countSave = blogService.saveBlog(blog);
			if(countSave<=0){
				String message = messageSource.getMessage("save.fail",new Object[]{}, request.getLocale());
				logger.info(message);
				return Result.build(400,message);
			}
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.build(500, message);
		}
		String message = messageSource.getMessage("save.success",new Object[]{}, request.getLocale());

		return Result.successAndMsg(message);
	}


	/**
	 * 进入查看页面
	 */
	@RequestMapping(value = "view", method = RequestMethod.GET)
	@MethodName(value="博客管理->博客内容管理->查看",type=2)
	@RequiresPermissions("oms:blog:content:view")
	public ModelAndView view(ModelAndView modelAndView,HttpServletRequest request,Long id) {
		try {
			Blog blog = blogService.selectByKey(id);
			modelAndView.addObject("blog",blog);
			modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"blog/content/view");
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		return modelAndView;
	}

	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.GET)
	@RequiresPermissions("oms:blog:content:update")
	public ModelAndView update(ModelAndView modelAndView, HttpServletRequest request, Long id) {
		try {
			Blog blog= blogService.selectByKey(id);
			modelAndView.addObject("blog",blog);
			modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"blog/content/update");
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		return modelAndView;
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("update")
	@RequiresPermissions("oms:blog:content:update")
	@MethodName(value="博客管理->博客内容管理->修改",type=2)
	synchronized public Result updateIcon(HttpServletRequest request, BlogVO blogVO, Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();

			Blog blog = dozerBeanMapper.map(blogVO,Blog.class);
			blog.setUpdateTime(new Date());
			blog.setUpdateBy(sysUser.getLoginname());
			int count = blogService.updateBlog(blog);
			if(count<=0){
				String message = messageSource.getMessage("save.fail",new Object[]{}, request.getLocale());
				logger.info(message);
				return Result.build(400,message);
			}
		} catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.build(500, message);
		}
		String message = messageSource.getMessage("save.success",new Object[]{}, request.getLocale());

		return Result.successAndMsg(message);
	}

	/**
	 * 删除图标
	 */
	@ResponseBody
	@RequestMapping("delete")
	@RequiresPermissions("oms:blog:content:delete")
	@MethodName(value="博客管理->博客内容管理->删除",type=2)
	public Result deleteArticle(HttpServletRequest request, Long id) {
		try {
			if (id==null) {
				String message = messageSource.getMessage("parameter.error",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.build(400,message);
			}
			int deleteCount = blogService.delete(id);
			if(deleteCount<=0){
				String message = messageSource.getMessage("delete.fail",new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.build(400,message);
			}
		} catch(Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.build(500,message);
		}
		String message = messageSource.getMessage("delete.success",new Object[]{}, request.getLocale());
		logger.info(message);
		return Result.success(200,message);

	}
}
